<template>
  <div class="novelist-container">
    <!-- 顶部导航栏 -->
    <div class="nav-bar">
      <div class="nav-left">
        <h2>AI小说创作助手</h2>
      </div>
      <div class="nav-right">
        <div class="connection-status" :class="{ 'connected': isConnected }">
          <el-tag :type="isConnected ? 'success' : 'danger'" size="small">
            {{ isConnected ? 'AI服务已连接' : 'AI服务未连接' }}
          </el-tag>
          <el-button 
            v-if="!isConnected" 
            type="primary" 
            size="small" 
            @click="reconnectWebSocket"
            :loading="isReconnecting"
          >
            重新连接
          </el-button>
        </div>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="main-content">
      <!-- 左侧面板 -->
      <div class="left-panel">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="角色设定" name="characters">
            <div class="character-panel">
              <div class="panel-header">
                <h3>角色列表</h3>
                <el-button type="primary" @click="showCharacterDialog">创建新角色</el-button>
              </div>
              <div class="character-list">
                <el-card v-for="char in characters" :key="char.id" class="character-card">
                  <template #header>
                    <div class="card-header">
                      <span>{{ char.name }}</span>
                      <el-button-group>
                        <el-button size="small" @click="editCharacter(char)">编辑</el-button>
                        <el-button size="small" type="danger" @click="deleteCharacter(char.id)">删除</el-button>
                      </el-button-group>
                    </div>
                  </template>
                  <div class="character-info">
                    <p><strong>背景：</strong>{{ char.background }}</p>
                    <p><strong>性格：</strong>{{ char.personality }}</p>
                    <p><strong>动机：</strong>{{ char.motivation }}</p>
                  </div>
                </el-card>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="大纲管理" name="outline">
            <div class="outline-panel">
              <div class="panel-header">
                <h3>故事大纲</h3>
                <el-button type="primary" @click="generateOutline">生成大纲</el-button>
              </div>
              <div class="outline-tree">
                <el-tree
                  :data="outlineData"
                  node-key="id"
                  default-expand-all
                  draggable
                  @node-drop="handleOutlineDrop"
                >
                  <template #default="{ node, data }">
                    <div class="outline-node">
                      <span>{{ data.title }}</span>
                      <el-button-group>
                        <el-button size="small" @click="editOutlineNode(data)">编辑</el-button>
                        <el-button size="small" type="danger" @click="deleteOutlineNode(data.id)">删除</el-button>
                      </el-button-group>
                    </div>
                  </template>
                </el-tree>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="世界观设定" name="world">
            <div class="world-panel">
              <div class="panel-header">
                <h3>世界观设定</h3>
              </div>
              <el-form :model="worldSettings" label-width="100px">
                <el-form-item label="世界类型">
                  <el-select v-model="worldSettings.type">
                    <el-option label="架空" value="fantasy" />
                    <el-option label="未来" value="future" />
                    <el-option label="魔法" value="magic" />
                    <el-option label="现实主义" value="realistic" />
                  </el-select>
                </el-form-item>
                <el-form-item label="时间背景">
                  <el-input v-model="worldSettings.timeBackground" type="textarea" />
                </el-form-item>
                <el-form-item label="地理环境">
                  <el-input v-model="worldSettings.geography" type="textarea" />
                </el-form-item>
                <el-form-item label="社会制度">
                  <el-input v-model="worldSettings.socialSystem" type="textarea" />
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 中央编辑区 -->
      <div class="main-editor">
        <div class="editor-toolbar">
          <div class="toolbar-left">
            <el-button-group>
              <el-button @click="generateContent">AI续写</el-button>
              <el-button @click="adjustStyle">调整风格</el-button>
              <el-button @click="getSuggestions">获取建议</el-button>
            </el-button-group>
          </div>
          <div class="toolbar-right">
            <el-select v-model="writingStyle" placeholder="选择写作风格">
              <el-option label="简洁" value="concise" />
              <el-option label="诗意" value="poetic" />
              <el-option label="史诗" value="epic" />
              <el-option label="第一人称" value="first-person" />
              <el-option label="第三人称" value="third-person" />
            </el-select>
          </div>
        </div>
        <div class="editor-content">
          <el-input
            v-model="content"
            type="textarea"
            :rows="20"
            placeholder="开始创作你的故事..."
            @input="saveContent"
          />
        </div>
      </div>

      <!-- 右侧面板 -->
      <div class="right-panel">
        <div class="ai-suggestions">
          <div class="panel-header">
            <h3>AI建议</h3>
          </div>
          <div class="suggestion-list">
            <div v-for="(suggestion, index) in suggestions" :key="index" class="suggestion-item">
              {{ suggestion }}
            </div>
          </div>
        </div>
        <div class="inspiration-panel">
          <div class="panel-header">
            <h3>灵感激发</h3>
            <el-button @click="generateInspiration">生成灵感</el-button>
          </div>
          <div class="inspiration-content">
            <div v-for="(inspiration, index) in inspirations" :key="index" class="inspiration-item">
              {{ inspiration }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 角色编辑对话框 -->
    <el-dialog
      v-model="characterDialogVisible"
      :title="editingCharacter ? '编辑角色' : '创建新角色'"
      width="50%"
    >
      <el-form :model="characterForm" label-width="100px">
        <el-form-item label="角色名称">
          <el-input v-model="characterForm.name" />
        </el-form-item>
        <el-form-item label="背景故事">
          <el-input v-model="characterForm.background" type="textarea" />
        </el-form-item>
        <el-form-item label="性格特点">
          <el-input v-model="characterForm.personality" type="textarea" />
        </el-form-item>
        <el-form-item label="动机">
          <el-input v-model="characterForm.motivation" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="characterDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveCharacter">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'

// 状态管理
const content = ref('')
const worldType = ref('')
const writingStyle = ref('')
const activeTab = ref('characters')
const characterDialogVisible = ref(false)
const editingCharacter = ref(null)
const characters = ref([])
const outlineData = ref([])
const suggestions = ref([])
const inspirations = ref([])

// 表单数据
const characterForm = ref({
  name: '',
  background: '',
  personality: '',
  motivation: ''
})

const worldSettings = ref({
  type: '',
  timeBackground: '',
  geography: '',
  socialSystem: ''
})

// WebSocket连接
const ws = ref(null)
const wsUrl = 'wss://adminstore.saas.nbsaas.com/websocket'
const isConnected = ref(false)

// 重连状态
const isReconnecting = ref(false)

// 本地存储键名
const STORAGE_KEYS = {
  CONTENT: 'novelist_content',
  CHARACTERS: 'novelist_characters',
  OUTLINE: 'novelist_outline',
  WORLD_SETTINGS: 'novelist_world_settings',
  WRITING_STYLE: 'novelist_writing_style',
  SUGGESTIONS: 'novelist_suggestions',
  INSPIRATIONS: 'novelist_inspirations'
}

// 加载本地数据
const loadLocalData = () => {
  try {
    content.value = localStorage.getItem(STORAGE_KEYS.CONTENT) || ''
    characters.value = JSON.parse(localStorage.getItem(STORAGE_KEYS.CHARACTERS) || '[]')
    outlineData.value = JSON.parse(localStorage.getItem(STORAGE_KEYS.OUTLINE) || '[]')
    worldSettings.value = JSON.parse(localStorage.getItem(STORAGE_KEYS.WORLD_SETTINGS) || '{}')
    writingStyle.value = localStorage.getItem(STORAGE_KEYS.WRITING_STYLE) || ''
    suggestions.value = JSON.parse(localStorage.getItem(STORAGE_KEYS.SUGGESTIONS) || '[]')
    inspirations.value = JSON.parse(localStorage.getItem(STORAGE_KEYS.INSPIRATIONS) || '[]')
  } catch (error) {
    console.error('加载本地数据失败:', error)
    ElMessage.error('加载数据失败，请刷新页面重试')
  }
}

// 保存本地数据
const saveLocalData = (key, value) => {
  try {
    if (typeof value === 'object') {
      localStorage.setItem(key, JSON.stringify(value))
    } else {
      localStorage.setItem(key, value)
    }
  } catch (error) {
    console.error('保存本地数据失败:', error)
    ElMessage.error('保存数据失败')
  }
}

// 监听数据变化并保存
watch(content, (newValue) => saveLocalData(STORAGE_KEYS.CONTENT, newValue))
watch(characters, (newValue) => saveLocalData(STORAGE_KEYS.CHARACTERS, newValue), { deep: true })
watch(outlineData, (newValue) => saveLocalData(STORAGE_KEYS.OUTLINE, newValue), { deep: true })
watch(worldSettings, (newValue) => saveLocalData(STORAGE_KEYS.WORLD_SETTINGS, newValue), { deep: true })
watch(writingStyle, (newValue) => saveLocalData(STORAGE_KEYS.WRITING_STYLE, newValue))
watch(suggestions, (newValue) => saveLocalData(STORAGE_KEYS.SUGGESTIONS, newValue), { deep: true })
watch(inspirations, (newValue) => saveLocalData(STORAGE_KEYS.INSPIRATIONS, newValue), { deep: true })

// 角色相关方法
const showCharacterDialog = () => {
  editingCharacter.value = null
  characterForm.value = {
    name: '',
    background: '',
    personality: '',
    motivation: ''
  }
  characterDialogVisible.value = true
}

const editCharacter = (character) => {
  editingCharacter.value = character
  characterForm.value = { ...character }
  characterDialogVisible.value = true
}

const saveCharacter = () => {
  if (editingCharacter.value) {
    const index = characters.value.findIndex(c => c.id === editingCharacter.value.id)
    if (index !== -1) {
      characters.value[index] = { ...characterForm.value, id: editingCharacter.value.id }
    }
  } else {
    characters.value.push({
      ...characterForm.value,
      id: Date.now().toString()
    })
  }
  characterDialogVisible.value = false
  ElMessage.success('保存成功')
}

const deleteCharacter = (id) => {
  characters.value = characters.value.filter(c => c.id !== id)
  ElMessage.success('删除成功')
}

// 大纲相关方法
const generateOutline = () => {
  sendMessage('outline', {
    worldSettings: worldSettings.value,
    characters: characters.value
  })
}

const handleOutlineDrop = (draggingNode, dropNode) => {
  // 处理大纲节点拖拽
}

const editOutlineNode = (node) => {
  // TODO: 实现大纲节点编辑
}

const deleteOutlineNode = (id) => {
  const deleteNode = (nodes) => {
    for (let i = 0; i < nodes.length; i++) {
      if (nodes[i].id === id) {
        nodes.splice(i, 1)
        return true
      }
      if (nodes[i].children && deleteNode(nodes[i].children)) {
        return true
      }
    }
    return false
  }
  deleteNode(outlineData.value)
}

// 重连WebSocket
const reconnectWebSocket = async () => {
  if (isReconnecting.value) return
  
  isReconnecting.value = true
  try {
    if (ws.value) {
      ws.value.close()
    }
    await connectWebSocket()
  } catch (error) {
    console.error('重连失败:', error)
    ElMessage.error('重连失败，请稍后重试')
  } finally {
    isReconnecting.value = false
  }
}

// 修改WebSocket连接方法
const connectWebSocket = () => {
  return new Promise((resolve, reject) => {
    try {
      ws.value = new WebSocket(wsUrl)
      
      ws.value.onopen = () => {
        isConnected.value = true
        ElMessage.success('AI服务连接成功')
        resolve()
      }
      
      ws.value.onclose = () => {
        isConnected.value = false
        ElMessage.error('AI服务连接断开')
      }
      
      ws.value.onerror = (error) => {
        console.error('WebSocket错误:', error)
        ElMessage.error('AI服务连接错误')
        reject(error)
      }
      
      ws.value.onmessage = (event) => {
        try {
          const response = JSON.parse(event.data)
          handleAIResponse(response)
        } catch (error) {
          console.error('解析AI响应失败:', error)
        }
      }
    } catch (error) {
      console.error('WebSocket连接失败:', error)
      ElMessage.error('AI服务连接失败')
      reject(error)
    }
  })
}

// 处理AI响应
const handleAIResponse = (response) => {
  switch (response.type) {
    case 'content':
      content.value += response.data
      break
    case 'suggestion':
      suggestions.value.push(response.data)
      break
    case 'inspiration':
      inspirations.value.push(response.data)
      break
    case 'outline':
      outlineData.value = response.data
      break
    case 'style':
      content.value = response.data
      break
    default:
      console.warn('未知的响应类型:', response.type)
  }
}

// 修改发送消息方法，增加重连逻辑
const sendMessage = (type, data) => {
  if (!isConnected.value) {
    ElMessageBox.confirm(
      'AI服务未连接，是否尝试重新连接？',
      '连接提示',
      {
        confirmButtonText: '重新连接',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      reconnectWebSocket()
    }).catch(() => {
      ElMessage.warning('操作已取消')
    })
    return
  }
  
  try {
    ws.value.send(JSON.stringify({
      type,
      data,
      context: {
        worldSettings: worldSettings.value,
        characters: characters.value,
        writingStyle: writingStyle.value
      }
    }))
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败')
  }
}

// AI功能实现
const generateContent = () => {
  if (!content.value) {
    ElMessage.warning('请先输入一些内容')
    return
  }
  sendMessage('continue', content.value)
}

const adjustStyle = () => {
  if (!content.value) {
    ElMessage.warning('请先输入一些内容')
    return
  }
  sendMessage('style', {
    content: content.value,
    style: writingStyle.value
  })
}

const getSuggestions = () => {
  sendMessage('suggest', {
    content: content.value,
    context: {
      worldSettings: worldSettings.value,
      characters: characters.value
    }
  })
}

const generateInspiration = () => {
  sendMessage('inspire', {
    worldSettings: worldSettings.value,
    characters: characters.value
  })
}

// 生命周期钩子
onMounted(() => {
  loadLocalData()
  connectWebSocket()
})

onUnmounted(() => {
  if (ws.value) {
    ws.value.close()
  }
})
</script>

<style scoped>
.novelist-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f7fa;
}

.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 60px;
  background-color: white;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.nav-left h2 {
  margin: 0;
  color: #303133;
  font-size: 20px;
}

.nav-right {
  display: flex;
  align-items: center;
}

.connection-status {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.connection-status.connected {
  background-color: #f0f9eb;
}

.main-content {
  display: grid;
  grid-template-columns: 300px 1fr 300px;
  gap: 20px;
  padding: 20px;
  flex: 1;
  overflow: hidden;
}

.left-panel, .right-panel {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.main-editor {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.panel-header h3 {
  margin: 0;
  color: #303133;
  font-size: 16px;
}

.editor-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.editor-content {
  flex: 1;
  overflow: auto;
}

.character-panel, .outline-panel, .world-panel {
  height: 100%;
  overflow: auto;
}

.character-list {
  overflow: auto;
}

.character-card {
  margin-bottom: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.character-info {
  font-size: 14px;
  line-height: 1.5;
}

.character-info p {
  margin: 5px 0;
}

.outline-node {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.suggestion-list, .inspiration-content {
  flex: 1;
  overflow: auto;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  margin-top: 10px;
}

.suggestion-item, .inspiration-item {
  padding: 8px;
  margin-bottom: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 14px;
}

:deep(.el-tabs__content) {
  height: calc(100% - 40px);
  overflow: auto;
}

:deep(.el-tree) {
  background: transparent;
}
</style>
